<?php
class Place_PlaceCommentController extends Zend_Controller_Action{
    
    
    public function init(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        $userSession = new Zend_Session_Namespace('user_session');
        $userSession->setExpirationSeconds($constants->SESSION_TIMEOUT);
        $user = $userSession->user;
        $userId = $user->sale_user_id;
        try{
            if(isset($userId)){
                // $userRoleModel = new Admin_Model_SaleUserRole();
                // $userRole = $userRoleModel->getRoleOfUser($userId);
//                 
                // $saleUserRoleFeature = new Admin_Model_SaleUserRoleFeature();
                // $featureArr = $saleUserRoleFeature->getFeatureOfUserRole($userRole);
                // $featureIdArr = array();
                // foreach ($featureArr as $key => $value) {
                    // array_push($featureIdArr,$value->sale_feature_id);
                // }
                // if(!in_array($constants->FEATURE_APPROVE_DEAL, $featureIdArr)){
                    // $this->_redirect('/admin/index');
                // }
                $this->view->title = "Approve Deal";    
                $this->view->userName = $user->full_name;
                
            }else{
                $this->_redirect('/place/index/index');
            }   
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }

    public function isUserExistedAction(){
        $this -> _helper -> viewRenderer -> setNoRender(true);
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        try{
            if(!isset($_GET['user_id'])){
                throw new Exception($constants->ERROR_STRING);
            }
            $userId = $_GET['user_id'];
            $adminGlobalUserModel = new Place_Model_AdminGlobalUser();
            $existUser = $adminGlobalUserModel->getUserById($userId);
            if(!empty($existUser)){
                echo $existUser[0]->nick_name;
            }else{
                echo $constants->ALERT_USER_NOT_EXIST;
            }
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }

    public function indexAction(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        try{
            if(!isset($_GET['place_id'])){
                throw new Exception($constants->ERROR_STRING);
            }
            
            $placeId = $_GET['place_id'];
            $merchantPlaceModel = new Place_Model_MerchantPlace();
            $place = $merchantPlaceModel->getPlaceDetail($placeId);
            
            $userSession = new Zend_Session_Namespace('user_session');
            $user = $userSession->user;
            $userId = $user->sale_user_id;
            
            $userRoleModel = new Place_Model_SaleUserRole();
            $userRole = $userRoleModel->getRoleOfUser($userId);
            
            $saleUserRoleFeature = new Place_Model_SaleUserRoleFeature();
            $featureArr = $saleUserRoleFeature->getFeatureOfUserRole($userRole);
            $featureIdArr = array();
            foreach ($featureArr as $key => $value) {
                array_push($featureIdArr,$value->sale_feature_id);
            }
            if(!in_array($constants->FEATURE_CHECK_PLACE, $featureIdArr)){
                $this->_redirect('/place/index/index');
            }
            $this -> view -> userFeature = $featureArr;
            
            $rateArr = array(1,2,3,4,5);
            
            $this->view->rateArr = $rateArr;
            $this->view->place = $place;
            $this->view->placeId = $placeId;
            
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }

    public function loadPlaceCommentAction(){
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        try{
            $page = 1;
            if(isset($_GET['page'])){
                $page = $_GET['page'];
            }
            if(!isset($_GET['place_id'])){
                throw new Exception($constants->ERROR_STRING);
            }
            
            $placeId = $_GET['place_id'];
            
            $shardPlaceCommentModel = new Place_Model_ShardPlaceComment();
            $placeCommentList = $shardPlaceCommentModel->getCommentOfPlace($placeId, $page);
            
            $adminPlaceModel = new Place_Model_AdminPlace();
            $adminPlace = $adminPlaceModel->getAdminPlaceDetail($placeId);
            $commentNumber = $adminPlace->no_of_comment;
            
            $pageNumber = ceil($commentNumber/($constants->PAGING_NUMBER));
            $this->view->pageNumber = $pageNumber;
            $this->view->commentNumber = $commentNumber;
            $this->view->page = $page;
            $this->view->commentList = $placeCommentList;
            $this->view->placeId = $placeId;
            
        }catch(Exception $e){
            $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
            $logger = new Zend_Log($writer);
            $controller = $this->getRequest()->getControllerName();
            $action = $this->getRequest()->getActionName();
            $logger -> info($controller."|".$action."|".$e -> getMessage());
            echo $constants->ERROR_STRING;
        }
    }
    
    public function addCommentAction(){
        $this -> _helper -> viewRenderer -> setNoRender(true);
        $registry   = Zend_Registry::getInstance();
        $constants = $registry->constants;
        if(isset($_POST['place_id']) && isset($_POST['user_id']) &&
                isset($_POST['place_comment'])){
            
            $placeId = $_POST['place_id'];
            $placeComment = $_POST['place_comment'];
            $userId = $_POST['user_id'];
            $rate = $_POST['rate'];
            
            $normalUtils = new My_Utils_NormalUtils();
            $globalDb = $normalUtils->getNormalDb(0);
            $globalDb->beginTransaction();
            
            $shardUtils = new My_Utils_ShardUtils();
            $currentShard = $shardUtils->getShard($userId);
            $currentShard->beginTransaction();
            
            try{
                
                $utils = new My_Utils_Utils();
                $currentTime = $utils->getUnixTime();
                
                if($userId == 0){
                    throw new Exception($constants->ERROR_STRING);
                }
                
                $adminGlobalUserModel = new Place_Model_AdminGlobalUser();
                $existUser = $adminGlobalUserModel->getUserById($userId);
                if(empty($existUser)){
                    throw new Exception($constants->ALERT_USER_NOT_EXIST);
                }
                $commentDate = '';
                if(isset($_POST['comment_date'])){
                    $commentDate = $_POST['comment_date'];
                }
                
                $unixTime = $currentTime;
                $minDate = strtotime('2014-01-31');
                if($commentDate == '' || strlen($commentDate) == 0){
                    
                    $currentDateTimeStr = date("Y-m-d H:i:s");
                    $unixTime = $utils->randomTime('2014-01-31', $currentDateTimeStr);
                    
                    
                }else{
                    
                    $randomHour = rand(6, 24);
                    $randomMinute = rand(0, 59);
                    $commentTimeStr = $commentDate." $randomHour:$randomMinute:0";
                    
                    $unixTime = strtotime($commentTimeStr);
                    
                }
                                
                
                if($unixTime > $currentTime || $unixTime == 0 || $unixTime < $minDate){
                    throw new Exception($constants->DATE_RANGE_ERROR);
                }
                
                
                $adminPlaceModel = new Place_Model_AdminPlace();
                $adminPlace = $adminPlaceModel->getAdminPlaceDetail($placeId);
                $noOfComment = $adminPlace->no_of_comment;
                $noOfComment = $noOfComment + 1;
                      
                
                
                $placeCommentArrParams = array("user_id"=>$userId,
                                                "place_id"=>$placeId,
                                                "comment"=>$placeComment,
                                                "comment_time"=>$unixTime);
                $shardPlaceCommentModel = new Place_Model_ShardPlaceComment();
                $shardPlaceCommentModel->saveComment($placeCommentArrParams);
                    
                $adminPlaceModel = new Place_Model_AdminPlace();
                                
                $placeRateModel = new Place_Model_AdminPlaceRate();
                $isRatePlace = $placeRateModel->isRated($placeId, $userId);
                
                $adminPlaceArrParams = array();
                
                if($isRatePlace){
                    $adminPlaceArrParams = array("place_id"=>$placeId,
                                                "no_of_comment"=>$noOfComment);
                }else{
                    $noOfRate = $adminPlace->no_of_rate;
                    $currentRateValue = $adminPlace->rate;
                    $currentRateValue = ($currentRateValue*$noOfRate + $rate)/ ($noOfRate + 1);
                    $adminPlaceArrParams = array("place_id"=>$placeId,
                                                "no_of_comment"=>$noOfComment,
                                                "rate"=>$currentRateValue,
                                                "no_of_rate"=>($noOfRate+1));
                    
                    $placeRateArrParams = array("place_id"=>$placeId,
                                                "global_user_id"=>$userId,
                                                "rate"=>$rate,
                                                "rate_time"=>$unixTime);
                    
                    $placeRateModel->save($placeRateArrParams);
                }
                
                $adminPlaceModel->updatePlace($adminPlaceArrParams);
                try{
                    $memcache = new Memcache;
                    $memcache->connect($constants->MEMCACHE_SERVER, $constants->MEMCACHE_PORT);
                    $memcache->delete($constants->CACHE_PLACE_COMMENT.$placeId);
                    $memcache->delete($constants->CACHE_PLACE_DETAIL.$placeId);    
                }catch(Exception $e){
                    echo "memcached not enable";
                }
                
                $globalDb->commit();
                $currentShard->commit();
                
                echo $constants->ADD_COMMENT_SUCCESS;
                
            }catch(Exception $e){
                $globalDb->rollback();
                $currentShard->rollback();
                $writer = new Zend_Log_Writer_Stream(BASE_PATH.$constants->LOG_FOLDER.'production_'.date('Y_m_d').$constants->LOG_FILE_EXTENSION);
                $logger = new Zend_Log($writer);
                $controller = $this->getRequest()->getControllerName();
                $action = $this->getRequest()->getActionName();
                $logger -> info($controller."|".$action."|".$e -> getMessage());
                echo $constants->ERROR_STRING;
            }
        }
        
    }
}
